import { useCounterStore } from '@/store/counter.js'
import { API_BASE_URL } from '@/config.js'
const store = useCounterStore()
export function request(url, data = {}, method = 'GET') {
  const header = {
    'X-Platform': 'MiniApp' // 小程序端标识必传
  } // 初始化 header 对象

  if (store.userData.token) {
    header.token = `Bearer ${store.userData.token}` // 如果令牌存在，则设置授权头
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: API_BASE_URL + url,
      method: method,
      data: data,
      header: header, // 使用 header 对象
      success: (res) => {
        console.log(res)
        if (res.data.code == 401 && res.data.msg == 'token已过期') {
          uni.showLoading({
            title: '登录已过期',
            mask: true,
            duration: 2000,
            success: () => {
              store.showLoading = false
              store.userInfo = {}
              store.userData = {}
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/index/index'
                })
              }, 2000)
            }
          })
        }
        resolve(res.data)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}
